#!/usr/bin/env python

##############################################################################

# You may need to change these things, depending on your install locations

diffProgram = 'c:\\Program Files\\Araxis\\Araxis Merge 2001 Professional\\compare.exe'
sandboxBase = r'd:\Sandbox'

##############################################################################

import sys
import os
import os.path
import warnings

# The tempnam function below is vulnerable to symlink attacks, and so
# has a warning attached to it. We don't care.
warnings.filterwarnings('ignore', 'tempnam is a potential security risk', RuntimeWarning)

verbose = False

def listSandboxModules():
    return [m for m in os.listdir(sandbox) if os.path.isdir(os.path.join(sandbox, m))]
    
def findLocalFile(allModules, changedFile):
    '''Expect changedFile to look like \\<anything>\module\<anything else>'''

    changedFile = os.path.normpath(changedFile)

    splitFile = changedFile.split(os.path.sep)
    for i in range(len(splitFile)):
        for (module, directory) in allModules:
            if splitFile[i] == directory:
                localFile = os.path.join(sandbox, module, *splitFile[i:])
                if os.path.exists(localFile):
                    return localFile
    return None

def compareNewFile(fileName):
    # make a temporary file to compare against
    tempFileName = os.tempnam()
    t = file(tempFileName, 'wb')
    t.write('no local equivalent of ' + fileName + ' found\n')
    t.close()
    os.spawnl(os.P_NOWAIT, diffProgram, 'compare', tempFileName, fileName)


def listModules():
    allModules = []
    for m in os.listdir(sandbox):
        if m not in ['outputs', 'subscribe', 'buildlogs'] and os.path.isdir(os.path.join(sandbox, m)):
            for d in os.listdir(os.path.join(sandbox, m)):
                if d not in ['run', 'CVS', 'buildlogs', '.svn'] and os.path.isdir(os.path.join(sandbox, m, d)):
                    allModules.append((m, d))
    return allModules
            

            
def main(args=None):
    import optparse
    global verbose
    global sandbox
    
    if args == None:
        args = sys.argv[1:]

    usage = '\t%prog [options] <path>*\t\tor\n\n\t%prog [options]\n\t<path>\n\t<path>\n\t...'
    optParser = optparse.OptionParser(usage)
    optParser.add_option('--stream', metavar='STREAM', action='store', dest='stream', default='main',
                         help='look in the sandbox for STREAM')
    optParser.add_option('--verbose', action='store_true', dest='verbose', default=False)
    
    (options, args) = optParser.parse_args(args)

    sandbox = os.path.join(sandboxBase, options.stream)
    verbose = options.verbose


    if 0 == len(args):
        if verbose:
            print 'no command line arguments specified, reading from stdin'
        lines = str.split(sys.stdin.read())
        args = [line.strip()  for line in lines if line.lstrip().startswith(r'\\')]
    
    allModules = listModules()
    for arg in args:
        if not os.path.exists(arg):
            print 'The remote file does not exist:', arg
            continue
        
        localFile = findLocalFile(allModules, arg)
        if verbose:
            print 'localFile =', localFile
        if localFile:
            os.spawnl(os.P_NOWAIT, diffProgram, 'compare', '/max', localFile, arg)
        else:
            if verbose:
                print "Can't find a local equivalent of", arg, "opening alone"

            compareNewFile(str(arg))
    return 0


if __name__ == '__main__':
    sys.exit(main())

